// 模块导入
import database from '../../utils/database'
// 评价表名
const evaluationTableName = 'Evaluation'
// 用户表名
const usersTableName = 'users'

// 定义评价模型接口
export interface EvaluationItem {
    id?: number;            // 标识
    user_id?: number;        // 发布者id
    gid?: number;            // 商品id
    created_at?: string;    // 创建时间
    state?: number;          // 审核状态
    content?: string;       // 评价内容
    star?: number;          // 评分 
}

// 评价服务类
export class EvaluationService {
    // 创建评价
    createEvaluation(e: EvaluationItem) {
        return new Promise((resolve, reject)=>{
            let keys = ['user_id', 'gid', 'content', 'star', 'state']
            let values = [e.user_id, e.gid, e.content, e.star, e.state]
            database.insertData(evaluationTableName, keys, values, (data)=>{
                if (!data) {
                    reject("创建评价失败")
                } else {
                    resolve(null)
                }
            })
        })
    }

    // 更新评价
    updateEvaluation(e: EvaluationItem) {
        return new Promise((resolve, _reject)=>{
            database.updateData(evaluationTableName, `state='${e.state}'`, `id = ${e.id}`)
            resolve(null)
        }) 
    }

    // 获取评价列表
    getList(gid: number | undefined = undefined, filter: number, offset: number, limit: number) {
        return new Promise((resolve, reject)=>{
            // 要查询的评价数据字段
            let keys = ['id', 'user_id', 'gid', 'content', 'star', 'created_at', 'state']
            let where = ''
            // 筛选条件与分页
            if (gid) {
                where += `gid=${gid}`
            } else {
                where += 'id IS NOT NULL'
            }
            where += ` and state=${filter}`
            where += ` limit ${limit} offset ${offset}`
            // 查询评价数据，同时将用户信息展开
            database.queryDataFrom(evaluationTableName, keys, [['id', 'username']], [usersTableName], ['user_id'], ['user'], where, (data)=>{
                if (!data) {
                    reject("获取评价数据失败")
                } else {
                    let result = data.result
                    resolve(result)
                }
            })
        });
    }
}
// 导出服务类
export default new EvaluationService();
